#include"pathstack.h"
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int init_stack(path_stack_t *s){
    if(s == NULL){
        return -1;
    }
    s->top=-1;//表示为空栈
    for(int i = 0;i <MAX_DEPTH; ++i){
        s->dirs[i]=NULL; 
    }
    return 0 ; 
}

int push_dir(path_stack_t *s,const char *dir){
    //该线程的目录栈 和 当前要去往的目录项
    if(s->top >=MAX_DEPTH-1){
        fprintf(stderr,"PATH STACK IS FULL.'%s'.\n",dir);
        return -1;//栈已满
    }
    char *curdir = (char*)malloc(strlen(dir)+1);
    if(curdir == NULL){
        fprintf(stderr,"Failed in malloc.\n");
    }
    strcpy(curdir,dir);
    s->top++;
    s->dirs[s->top]=curdir;
    return 0;

}

char * pop_dir(path_stack_t *s){
    if(s->top == -1){
        printf("stderr,Stack Empty!\n");
        return NULL;
    }
    char *popped_dir = s->dirs[s->top];
    s->dirs[s->top]=NULL;

    s->top--;
    return popped_dir;

}
int free_stack(path_stack_t *s){
    if(s==NULL){
        return 0;
    }
    for(int i = 0 ; i < s->top;i++){
        free(s->dirs[i]);
        s->dirs[i]=NULL;
    }
    s->top=-1;
    return 0;
}

